﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq.Expressions;
using Aragorn.SOA.ORM.Lambda;

namespace Aragorn.SOA.ORM
{
    public class DeleteExpressionCommand<T> : SqlLamCommandBase
       where T : class
    {
        private SqlLam<T> query;

        private DbContextData Data
        {
            get;
            set;
        }

        public DeleteExpressionCommand(DbContextData contextData, Expression<Func<T, bool>> expression)
        {
            this.Data = contextData;
            if (expression == null)
            {
                this.query = new SqlLam<T>();
                return;
            }
            this.query = (new SqlLam<T>()).Where(expression);
        }

        public DeleteExpressionCommand(DbContextData contextData)
        {
            this.Data = contextData;
            this.query = new SqlLam<T>();
        }

        public DeleteExpressionCommand<T> And(Expression<Func<T, bool>> expression)
        {
            this.query = this.query.And(expression);
            return this;
        }

        public int Execute()
        {
            if (this.query == null)
            {
                throw new Exception("删除数据，请设置过滤条件;如果没有条件，可以设置1==1");
            }
            CommandType? nullable = null;
            return this.Data.Connection.Execute(this.query.DeleteString, this.Data, this.query.QueryParameters, this.Data.Transaction, this.Data.CommandTimeout, nullable);
        }

        internal override SqlLamBase GetBaseQuery()
        {
            return this.query;
        }

        public DeleteExpressionCommand<T> Or(Expression<Func<T, bool>> expression)
        {
            this.query = this.query.Or(expression);
            return this;
        }

        public DeleteExpressionCommand<T> Where(Expression<Func<T, bool>> expression)
        {
            this.query = (new SqlLam<T>()).Where(expression);
            return this;
        }

        public DeleteExpressionCommand<T> WhereIsIn(Expression<Func<T, object>> expression, SqlLamCommandBase sqlQuery)
        {
            this.query = this.query.WhereIsIn(expression, sqlQuery.GetBaseQuery());
            return this;
        }

        public DeleteExpressionCommand<T> WhereIsIn(Expression<Func<T, object>> expression, IEnumerable<object> values)
        {
            this.query = this.query.WhereIsIn(expression, values);
            return this;
        }

        public DeleteExpressionCommand<T> WhereNotIn(Expression<Func<T, object>> expression, SqlLamCommandBase sqlQuery)
        {
            this.query = this.query.WhereNotIn(expression, sqlQuery.GetBaseQuery());
            return this;
        }

        public DeleteExpressionCommand<T> WhereNotIn(Expression<Func<T, object>> expression, IEnumerable<object> values)
        {
            this.query = this.query.WhereNotIn(expression, values);
            return this;
        }
    }
}